import os
import subprocess
import shutil
from pathlib import Path
from typing import Dict, List
from util import gifToMp4


def list_all_dir_names(root_dir: str) -> Dict[str, str]:
    """获取目录下所有文件夹的名称和路径"""
    return {
        os.path.basename(dir_path): os.path.abspath(dir_path)
        for dir_path, _, _ in os.walk(root_dir)
        if os.path.isdir(dir_path) and dir_path != root_dir
    }


def list_all_file_names(dir_path: str) -> List[str]:
    """获取目录下所有文件的名称（带完整路径）"""
    return [
        os.path.join(dir_path, filename)
        for filename in os.listdir(dir_path)
        if os.path.isfile(os.path.join(dir_path, filename))
    ]



def main(base_path : str):
    # 获取素材文件夹下所有子文件夹
    sc_dir_names = list_all_dir_names(base_path)

    # 获取每个子文件夹下的所有文件
    sc_dir_files = {k: list_all_file_names(v) for k, v in sc_dir_names.items()}

    # 存储有问题的文件
    error_files = {}

    # 检查每个文件
    for k, v in sc_dir_files.items():
        error_file = []
        for s in v:

            # 构建ffmpeg命令
            result = subprocess.run(
                [
                    "ffmpeg",
                    "-i", s
                ],  # 命令参数以列表形式传递（更安全）
                capture_output=True,  # 捕获stdout和stderr
                text=True,  # 以文本形式返回（否则是bytes）
                shell=True,  # Windows需设为True，Linux/macOS通常不需要
            encoding = "utf-8"  # 显式指定 UTF-8 编码
            )
            print(s)
            # 执行ffmpeg命令
            if result.stderr is not None and "image data not found" in result.stderr:
                error_file.append(s)
        error_files[k] = error_file
    print(error_files)
    # 移动有问题的文件到temp文件夹
    for k, v in error_files.items():
        for s in v:
            source_path = Path(s)
            target_dir = source_path.parent / "temp"
            target_path = target_dir / source_path.name
            try:
                # 确保目标目录存在
                target_dir.mkdir(parents=True, exist_ok=True)
                # 移动文件
                shutil.move(source_path, target_path)
                print("文件移动成功！")
            except Exception as e:
                print(f"文件移动失败: {e}")
                e.printStackTrace()

    folders  = gifToMp4.list_folders(base_path)

    for folder_name in folders:
        print(folder_name)  # 输出文件夹名称

        # 替换为实际存放 webp 文件的文件夹路径
        input_folder_path = base_path + "\\"+folder_name +"\\temp"
        if not os.path.exists(input_folder_path):
            print(f"目录 {input_folder_path} 不存在！")
            continue

        # 替换为实际要保存 MP4 文件的文件夹路径
        output_folder_path = base_path + "\\"+folder_name
        gifToMp4.convert_gif_to_mp4(input_folder_path, output_folder_path)
        gifToMp4.shutil.rmtree(input_folder_path)  # 递归删除所有文件和子文件夹




if __name__ == "__main__":
    main(r"C:\Users\haoxi\Desktop\新表情包素材")
